import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import 'school_grade_subject_view_model.dart';

/// 学校年级科目-视图-新增
class SchoolGradeSubjectViewEdit extends StatefulWidget {
  final String schoolId;
  final String? id;

  const SchoolGradeSubjectViewEdit({
    super.key,
    required this.schoolId,
    this.id,
  });

  @override
  State<SchoolGradeSubjectViewEdit> createState() =>
      _SchoolGradeSubjectViewEditState();
}

class _SchoolGradeSubjectViewEditState
    extends State<SchoolGradeSubjectViewEdit> {
  final formKey = GlobalKey<FormState>();

  int scoreValue = 100;
  double discount = 1.0;

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<SchoolGradeSubjectViewModel>();
    model.loadInit(widget.schoolId, afterHandler: () => loadData(model));
  }

  void loadData(final SchoolGradeSubjectViewModel model) {
    final id = widget.id ?? '';
    if (id.isEmpty) {
      model.cleanInputFields();
      return;
    }
    model.getInfoById(id);
  }

  void popHandler(final bool ret) => context.pop<bool>(ret);

  void onSaveHandler(final SchoolGradeSubjectViewModel model) {
    if (formKey.currentState?.validate() ?? false) {
      final id = widget.id ?? '';
      if (id.isNotEmpty) {
        //修改处理
        model.onModifyHandler(id, () => popHandler(true));
        return;
      }
      //新增处理
      model.onAddHandler(widget.schoolId, () => popHandler(true));
    }
  }

  @override
  Widget build(final BuildContext context) =>
      Consumer<SchoolGradeSubjectViewModel>(
        builder: (_, model, __) => ScaffoldPage.withPadding(
          content: buildForm(model),
          bottomBar: Padding(
            padding: EdgeInsetsDirectional.only(bottom: 20.h),
            child: OverflowBar(
              spacing: 2.w,
              children: [
                //保存
                buttons.save(onPressed: () => onSaveHandler(model)),
                //取消
                buttons.cancel(onPressed: () => popHandler(false)),
              ],
            ),
          ),
        ),
      );

  Widget buildForm(final SchoolGradeSubjectViewModel model) {
    final isAdd = (widget.id ?? '').isEmpty;
    Widget buildContainer(Widget child) => Container(
          padding: EdgeInsetsDirectional.symmetric(vertical: 10.h),
          constraints: BoxConstraints(maxWidth: 268.w),
          child: child,
        );
    Widget buildWidget(String label, Widget child) => buildContainer(
          InfoLabel(
            label: label,
            child: child,
          ),
        );
    Widget buildCombobox(SchoolGradeSubjectInputField field,
        List<ComboBoxItem<String>> Function() handler) {
      final label = field.label;
      void valChangedHandler(final String? val) {
        if (val == null || val.isEmpty) {
          return;
        }
        final c = model.getController(field);
        c?.text = val;
      }

      return buildWidget(
        label,
        ComboboxFormField(
          placeholder: Text(label),
          items: handler.call(),
          value: model.getFieldValue(field),
          onChanged: (val) => valChangedHandler(val),
        ),
      );
    }

    Widget buildText(SchoolGradeSubjectInputField field) => buildWidget(
          field.label,
          TextFormBox(
            controller: model.getController(field),
            placeholder: field.label,
            maxLines: field == SchoolGradeSubjectInputField.remark ? 3 : null,
            validator: (val) => field.validHandler(val),
          ),
        );
    Widget buildNumber(SchoolGradeSubjectInputField field, bool isRate,
        void Function(num? val)? handler) {
      final label = field.label;
      final c = model.getController(field);
      return buildWidget(
        field.label,
        NumberFormBox(
          min: 0,
          max: isRate ? 1 : 150,
          placeholder: label,
          smallChange: isRate ? 0.1 : 10,
          mode: SpinButtonPlacementMode.inline,
          validator: (val) => field.validHandler(val),
          value: () {
            final defVal = model.getFieldValue(field) ?? '';
            return isRate ? double.tryParse(defVal) : int.tryParse(defVal);
          }(),
          onChanged: (val) {
            if (val != null) {
              c?.text = '$val';
              if (handler != null) {
                handler(val);
              }
            }
          },
        ),
      );
    }

    Widget buildSwitch() {
      final field = SchoolGradeSubjectInputField.status;
      final controller = model.getController(field);
      final child = ToggleSwitch(
        checked: () {
          final String val = controller?.text ?? '0';
          return (int.tryParse(val) ?? 0) == 1;
        }(),
        onChanged: (val) => setState(() => controller?.text = '${val ? 1 : 0}'),
      );
      return buildWidget(field.label, child);
    }

    return Form(
      key: formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //学年学期
          buildCombobox(
            SchoolGradeSubjectInputField.semester,
            () => model.semestersBySchool(widget.schoolId),
          ),
          //年级
          buildCombobox(
            SchoolGradeSubjectInputField.grade,
            () => model.gradesBySchool(widget.schoolId),
          ),
          //学科
          buildCombobox(
            SchoolGradeSubjectInputField.subject,
            () => model.subjectOpts,
          ),
          //默认分值
          buildNumber(
            SchoolGradeSubjectInputField.scoreValue,
            false,
            (val) => setState(() => scoreValue = val as int),
          ),
          //折算比例
          buildNumber(
            SchoolGradeSubjectInputField.discount,
            true,
            (val) => setState(() => discount = val as double),
          ),
          //折后分值
          buildWidget('折后分', Text('${scoreValue * discount}')),
          //备注
          buildText(SchoolGradeSubjectInputField.remark),
          //状态
          if (!isAdd) buildSwitch(),
        ],
      ),
    );
  }
}
